package com.lam.mall.controller;

import java.util.Date;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.lam.common.base.controller.BaseController;
import com.lam.common.base.domain.Result;
import com.lam.common.components.dict.annotation.DictAutoTransfer;
import com.lam.common.constant.CommonConstant;
import com.lam.common.constant.MallStateConstant;
import com.lam.common.context.TokenUtils;
import com.lam.common.exception.BusinessException;
import com.lam.common.exception.ParameterErrorException;
import com.lam.common.utils.NumberUtil;
import com.lam.common.utils.StringUtils;
import com.lam.common.validate.ValidateUtil;
import com.lam.common.validate.group.Add;
import com.lam.common.validate.group.Update;
import com.lam.common.validate.model.ValidOperType;
import com.lam.framework.annotation.ParamInject;
import com.lam.framework.operLog.annotation.Log;
import com.lam.framework.operLog.enums.BusinessType;
import com.lam.mall.common.constant.MallConstant;
import com.lam.mall.entity.ProdSku;
import com.lam.mall.entity.Product;
import com.lam.mall.param.ProductParam;
import com.lam.mall.service.ProductService;

import cn.hutool.core.collection.CollectionUtil;

/**
 * 商品管理Controller
 * 
 * @author admin
 * @date 2023-04-20
 */
@Log(title = "商品管理")
@ParamInject
@RestController
@RequestMapping("/${adminPath}/mall/product")
public class ProductController extends BaseController {

    @Autowired
    private ProductService productService;

    /**
     * 查询商品管理列表
     */
    @Log(oper="分页查询")
    @DictAutoTransfer
    @PreAuthorize("@ss.hasPm('mall:product:list')")
    @GetMapping("/list")
    public Result list(ProductParam param) {
    	
    	if(param.getStatus() != null && param.getStatus() == -1) {
    		param.setStatus(null);
    	}
    	param.setShopId(TokenUtils.getLoginUserShopId());
    
        startPage();
        orderByColumn("putaway_time", "desc");
        List<Product> list = productService.selectList(param);
        return Result.ok(getTableData(list));
    }

    /**
     * 获取商品管理详细信息
     */
    @DictAutoTransfer
    @Log(oper="根据ID查询")
    @PreAuthorize("@ss.hasPm('mall:product:query')")
    @GetMapping("/{id}")
    public Result getInfo(@PathVariable("id") String id) {
    
        return Result.ok(productService.selectById(id, true));
    }

    /**
     * 新增商品管理
     */
    @PreAuthorize("@ss.hasPm('mall:product:add')")
    @Log(businessType = BusinessType.INSERT)
    @PostMapping
    public Result add(@Validated(Add.class) @RequestBody Product product) {
    
    	product.setShopId(TokenUtils.getLoginUserShopId());
    	ValidateUtil.validUnique(product, ValidOperType.ADD, MallConstant.UNIQUE_PRODUCT_PROD_NAME, "商品名称已存在！");
    	checkParam(product);
    	
    	product.convertProperties(false);
    	
        product.setShopId(TokenUtils.getLoginUserShopId());
        product.setCreateTime(new Date());
        product.setUpdateTime(new Date());
        if (NumberUtil.eq(product.getStatus(), MallStateConstant.STATUS_ONLINE)) {
            product.setPutawayTime(new Date());
        }
        productService.insert(product);
        return Result.ok();
    }
    
    private void checkParam(Product product) {
        if (CollectionUtil.isEmpty(product.getTagList())) {
            throw new BusinessException("请选择产品分组");
        }

        List<ProdSku> skuList = product.getSkuList();
        boolean isUseSku = false;
        for (ProdSku sku : skuList) {
            if (NumberUtil.eq(sku.getStatus(), CommonConstant.STATUS_NORMAL_1)) {
            	isUseSku = true;
                break;
            }
        }
        if (!isUseSku) {
            throw new ParameterErrorException("至少要启用一种商品规格");
        }
    }

    /**
     * 修改商品管理
     */
    @PreAuthorize("@ss.hasPm('mall:product:edit')")
    @Log(businessType = BusinessType.UPDATE)
    @PutMapping
    public Result edit(@Validated(Update.class) @RequestBody Product product) {
    
    	ValidateUtil.validUnique(product, ValidOperType.UPDATE, MallConstant.UNIQUE_PRODUCT_PROD_NAME, "商品名称已存在！");
    	checkParam(product);
    	
    	product.convertProperties(false);
    	product.setUpdateTime(new Date());
        int n = productService.update(product);
        if(n > 0) {
        	productService.removeProductCacheById(product.getId());
        }
        return Result.ok();
    }
    
    /**
     * 上架商品
     */
    @PreAuthorize("@ss.hasPm('mall:product:putOn')")
    @Log(businessType = BusinessType.UPDATE, oper = "上架商品")
    @PostMapping("/putOn")
    public Result putOn(@RequestBody Product product) {
    	
    	ValidateUtil.validRequired(product.getId(), "商品ID不能为空！");
    	product.setStatus(MallStateConstant.STATUS_ONLINE);
    	for (String i : StringUtils.str2List(product.getId())) {
    		product.setId(i);
    		int n = productService.updateStatus(product);
            if(n > 0) {
            	productService.removeProductCacheById(product.getId());
            }
		}
        return Result.ok();
    }
    
    /**
     * 下架商品
     */
    @PreAuthorize("@ss.hasPm('mall:product:putOff')")
    @Log(businessType = BusinessType.UPDATE, oper = "下架商品")
    @PostMapping("/putOff")
    public Result putOff(@RequestBody Product product) {
    	
    	ValidateUtil.validRequired(product.getId(), "商品ID不能为空！");
    	product.setStatus(MallStateConstant.STATUS_OFFLINE);
    	for (String i : StringUtils.str2List(product.getId())) {
    		product.setId(i);
    		int n = productService.updateStatus(product);
            if(n > 0) {
            	productService.removeProductCacheById(product.getId());
            }
		}
        return Result.ok();
    }

    /**
     * 删除商品管理
     */
    @PreAuthorize("@ss.hasPm('mall:product:remove')")
    @Log(businessType = BusinessType.DELETE)
    @DeleteMapping("/{id}")
    public Result remove(@PathVariable String id) {
    
    	int n = productService.deleteById(id);
        if(n > 0) {
        	for (String i : StringUtils.str2List(id)) {
        		productService.removeProductCacheById(i);
			}
        }
        return toAjax(productService.deleteById(id));
    }
    

}
